import useEvent from '@/hooks/useEvent';
import type { BaseEventOrig, InputProps } from '@tarojs/components';
import { useState } from 'react';

type Event = BaseEventOrig<InputProps.inputEventDetail>;

type ReturnValue = [string, (e: Event) => void, (v: string) => void]

export default function useInputState(defaultValue = '', formatter?: (value: string) => string): ReturnValue {
  const [value, setValue] = useState(defaultValue);
  const handleInput = useEvent((e: Event) => {
    const { value: newValue } = e.detail;
    setValue(newValue && (formatter ? formatter(newValue) : newValue));
  });

  return [value, handleInput, setValue];
}
